<template lang="pug">
  .loading    
</template>

<script>
import homeService from '@/api/home'
import tokenService from '@/api/token'
import router from '@/router'
import axios from 'axios'
const wechatConfig = require('../../wechatConfig')

export default {
  name: 'loading',
  methods: {
    checkIsReg (data) {
      if (data.scope === 'snsapi_base') {
        homeService.IsRegister({openid: data.openid})
        .then(res => {
          // localStorage.setItem('openid', res.result.uid)
          console.log('IsRegister', res)
          if (res.result.isreg) {
            homeService.Login()
              .then(res => {
                localStorage.setItem('uid', res.result.uid)
                router.replace('/index')
              })
          } else {
            router.replace('/licence')
          }
        })
      } else {
        // 获取用户详细信息 并注册
        console.log('snsapi_userinfo', data)
        var url = 'wechat/userinfo?access_token=' + data.access_token + '&openid=' + data.openid + '&lang=zh_CN'
        axios.get(url).then(user => {
          console.log('userInfo:', user.data)
          // debugger
          var params = user.data
          params.avatar = params.headimgurl
          homeService.Register(params).then(res => {
            homeService.Login()
              .then(res => {
                localStorage.setItem('uid', res.result.uid)
                router.replace('/index')
              })
          })
        })
      }
    },
    initApp () {
      // 1 解析code
      var locationQuery = {}
      window.location.search.slice(1).split('&').forEach(d => {
        var p = d.split('=')
        locationQuery[p[0]] = p[1]
      })
      console.log('locationQuery:', locationQuery)
      // 2 通过code换取网页授权access_token openid
      /**
       * access_token:"10_qHsgDPraLHm1eIO-guP9yRe57KaPWc_OkqliQPah7K0kvqwjuPcSIJ1bYHZr-0VC3nM1kSJkJm-fP4PEsdlC4g"
          expires_in:7200
          openid:"ocsRWwaP_sxcrgSVjBC3L4wmPjk4"
          refresh_token:"10_1SET272SFhjg7IvuRLjmUzrybFJQXq8LcWcYyn4RbU_UzUdXUbtIz_bodj6ihCp9tTJ99qU1qGEpOm7zVaWFXg"
          scope:"snsapi_base"
       */
      var apiUrl = '/wechat/oauth2/access_token?appid=' + wechatConfig.appID + '&secret=' + wechatConfig.appScrect + '&code=' + locationQuery.code + '&grant_type=authorization_code'
      axios.get(apiUrl).then(d => {
        console.log('access_token:', d)
        var access_token = d.data.access_token
        var openid = d.data.openid
        localStorage.setItem('openid', d.data.openid)
        // 3 检查是否注册
        if (localStorage.getItem('jwtToken')) {
          this.checkIsReg(d.data)
        } else {
          tokenService.AccessToken()
            .then(res => {
              // console.log(res)
              localStorage.setItem('jwtToken', res.result.token)
              this.checkIsReg(d.data)
            })
        }
      })
    },
    getOpenid () {
      var redirectUri = encodeURIComponent(window.location.href)
      var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wechatConfig.appID + '&redirect_uri=' + redirectUri + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
      window.location.href = url
    }
  },
  created () {
    // import axios from 'axios'
    // if()

    if (/code/.test(window.location)) {
      this.initApp()
    } else {
      // 1. 获取普通静默code
      this.getOpenid()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
  

</style>
